package com.chatbot.controller;

import com.chatbot.dto.ChatMessageDTO;
import com.chatbot.dto.ChatRequest;
import com.chatbot.dto.ConversationDTO;
import com.chatbot.dto.NewConversationRequest;
import com.chatbot.service.ChatService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class ChatController {

    private final ChatService chatService;

    public ChatController(ChatService chatService) {
        this.chatService = chatService;
    }

    @PostMapping("/conversations")
    public ResponseEntity<ConversationDTO> createConversation(
            Authentication authentication,
            @RequestBody NewConversationRequest request) {
        return ResponseEntity.ok(
                chatService.createConversation(authentication.getName(), request.getTitle())
        );
    }

    @GetMapping("/conversations")
    public ResponseEntity<List<ConversationDTO>> getConversations(Authentication authentication) {
        return ResponseEntity.ok(
                chatService.getUserConversations(authentication.getName())
        );
    }

    @GetMapping("/conversations/{conversationId}")
    public ResponseEntity<ConversationDTO> getConversation(
            Authentication authentication,
            @PathVariable Long conversationId) {
        return ResponseEntity.ok(
                chatService.getConversation(authentication.getName(), conversationId)
        );
    }

    @GetMapping("/conversations/{conversationId}/messages")
    public ResponseEntity<List<ChatMessageDTO>> getConversationMessages(
            Authentication authentication,
            @PathVariable Long conversationId) {
        ConversationDTO conversation = chatService.getConversation(authentication.getName(), conversationId);
        return ResponseEntity.ok(conversation.getMessages());
    }

    @PostMapping("/messages")
    public ResponseEntity<ChatMessageDTO> sendMessage(
            Authentication authentication,
            @RequestBody ChatRequest request) {
        return ResponseEntity.ok(
                chatService.sendMessage(
                        authentication.getName(),
                        request.getConversationId(),
                        request.getMessage()
                )
        );
    }

    @GetMapping(value = "/messages/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamMessage(
            Authentication authentication,
            @RequestParam Long conversationId,
            @RequestParam String message) {
        SseEmitter emitter = new SseEmitter(TimeUnit.MINUTES.toMillis(5)); // 5 minutes timeout
        
        emitter.onCompletion(() -> {
            // Clean up code if needed
        });
        
        emitter.onTimeout(() -> {
            emitter.complete();
        });
        
        try {
            return chatService.streamMessage(
                    authentication.getName(),
                    conversationId,
                    message
            );
        } catch (Exception e) {
            emitter.completeWithError(e);
            return emitter;
        }
    }

    @PostMapping(value = "/messages/attachment", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ChatMessageDTO> sendMessageWithAttachment(
            Authentication authentication,
            @RequestParam("conversationId") Long conversationId,
            @RequestParam(value = "message", required = false) String message,
            @RequestParam("files") List<MultipartFile> files) {
        return ResponseEntity.ok(
                chatService.sendMessageWithAttachment(
                        authentication.getName(),
                        conversationId,
                        message,
                        files
                )
        );
    }

    @GetMapping("/attachments/{attachmentId}")
    public ResponseEntity<Resource> downloadAttachment(
            Authentication authentication,
            @PathVariable Long attachmentId) {
        Resource resource = chatService.downloadAttachment(authentication.getName(), attachmentId);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @DeleteMapping("/conversations/{conversationId}")
    public ResponseEntity<Void> deleteConversation(
            Authentication authentication,
            @PathVariable Long conversationId) {
        chatService.deleteConversation(authentication.getName(), conversationId);
        return ResponseEntity.noContent().build();
    }
} 